<template>
  <div class="h-full w-full bg-gray-50 flex flex-col">
    <!-- 主要内容区域 - 根据内容自适应高度，不强制占满全屏 -->
    <div class="flex-1 p-6">
      <div class="w-full max-w-6xl mx-auto">
        <!-- 扫描状态指示器 -->
        <div class="text-center mb-6">
          <div class="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <svg class="w-8 h-8 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
            </svg>
          </div>
          <h2 class="text-2xl font-bold text-gray-900 mb-2">{{ currentStatus }}</h2>
          <p class="text-lg text-gray-600">{{ currentSubStatus }}</p>
        </div>

        <!-- 扫描完成提示 -->
        <div v-if="isScanCompleted" class="bg-green-50 border border-green-200 rounded-lg p-6 mb-6 text-center">
          <div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <svg class="w-8 h-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
          </div>
          <h3 class="text-xl font-semibold text-green-800 mb-2">扫描已完成</h3>
          <p class="text-green-600 mb-4">扫描进度页面已显示完成状态，您可以查看扫描结果或返回首页</p>
          <div class="flex justify-center space-x-4">
            <button 
              @click="$emit('navigate', 'results')"
              class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors"
            >
              查看扫描结果
            </button>
            <button 
              @click="$emit('navigate', 'home')"
              class="bg-gray-300 hover:bg-gray-400 text-gray-700 px-4 py-2 rounded-lg text-sm font-medium transition-colors"
            >
              返回首页
            </button>
          </div>
        </div>

        <!-- 总体进度 -->
        <div v-else class="bg-white rounded-lg border border-gray-200 p-4 mb-6">
          <div class="flex items-center justify-between mb-3">
            <h3 class="text-lg font-semibold text-gray-900">总体进度</h3>
            <span class="text-2xl font-bold text-blue-600">{{ scanProgress.percentage || 0 }}%</span>
          </div>
          <div class="w-full bg-gray-200 rounded-full h-3">
            <div 
              class="bg-blue-600 h-3 rounded-full transition-all duration-300 ease-out"
              :style="{ width: (scanProgress.percentage || 0) + '%' }"
            ></div>
          </div>
        </div>

        <!-- 实时进度日志 -->
        <div class="bg-gray-900 text-green-400 rounded-lg border border-gray-700 p-4 mb-4">
          <div class="flex items-center justify-between mb-3">
            <h3 class="text-lg font-semibold text-white">实时进度日志</h3>
            <div class="flex items-center space-x-2">
              <div class="flex items-center space-x-2">
                <div class="w-2 h-2 bg-green-500 rounded-full"></div>
                <span class="text-sm text-gray-300">自动滚动</span>
              </div>
            </div>
          </div>
          
          <!-- 日志内容区域 - 根据内容自适应高度，无滚动条 -->
          <div 
            ref="logContainerRef"
            class="min-h-40 max-h-60 overflow-y-auto bg-black rounded border border-gray-600 p-3 font-mono text-sm"
          >
            <div v-for="(log, index) in progressLogs" :key="index" class="mb-1">
              <span class="text-gray-400">[{{ formatTime(log.timestamp) }}]</span>
              <span class="text-green-400 ml-2">{{ log.message }}</span>
            </div>
            
            <!-- 当前扫描文件显示 -->
            <div v-if="currentFile" class="mt-2 p-2 bg-blue-900 bg-opacity-30 rounded border border-blue-700">
              <span class="text-blue-300">正在扫描:</span>
              <span class="text-white ml-2">{{ currentFile }}</span>
            </div>
            
            <!-- 空状态 -->
            <div v-if="progressLogs.length === 0" class="text-gray-500 text-center py-6">
              等待扫描开始...
            </div>
          </div>
        </div>

        <!-- 统计信息 - 紧凑布局 -->
        <div class="grid grid-cols-3 gap-4">
          <div class="bg-blue-50 p-3 rounded-lg border border-blue-200 text-center">
            <div class="text-xl font-bold text-blue-600">{{ localScannedFiles }}</div>
            <div class="text-sm text-blue-600">已扫描文件</div>
            <div class="text-xs text-blue-500 mt-1">{{ scannedFilesStatus }}</div>
          </div>
          <div class="bg-green-50 p-3 rounded-lg border border-green-200 text-center">
            <div class="text-xl font-bold text-green-600">{{ localDuplicateGroups }}</div>
            <div class="text-sm text-green-600">重复组数</div>
            <div class="text-xs text-green-500 mt-1">{{ duplicateGroupsStatus }}</div>
          </div>
          <div class="bg-purple-50 p-3 rounded-lg border border-purple-200 text-center">
            <div class="text-xl font-bold text-purple-600">{{ savedSpaceDisplay }}</div>
            <div class="text-sm text-purple-600">可节省空间</div>
            <div class="text-xs text-purple-500 mt-1">{{ savedSpaceStatus }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作按钮 - 使用flex布局确保位置正确 -->
    <div class="bg-white border-t border-gray-200 px-6 py-4 flex-shrink-0">
      <div class="flex justify-between items-center">
        <button 
          @click="$emit('navigate', 'home')"
          class="bg-gray-300 hover:bg-gray-400 text-gray-700 px-4 py-2 rounded-lg text-sm font-medium transition-colors"
        >
          <svg class="w-4 h-4 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
          </svg>
          返回首页
        </button>
        
        <button 
          @click="stopScan"
          class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors"
        >
          <svg class="w-4 h-4 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
          </svg>
          停止扫描
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from 'vue'

interface ScanProgress {
  scannedFiles?: number
  duplicateGroups?: number
  savedSpace?: number
  stage?: string
  status?: string
  subStatus?: string
  message?: string
  percentage?: number // 新增：用于显示动态进度
}

interface ProgressLog {
  timestamp: number
  message: string
}

interface Props {
  scanProgress: ScanProgress
  isScanning: boolean
}

const props = defineProps<Props>()

// 定义事件
const emit = defineEmits<{
  'cancel-scan': []
  'navigate': [route: string]
}>()

// 进度日志
const progressLogs = ref<ProgressLog[]>([])
const currentFile = ref('')
const logContainerRef = ref<HTMLElement>()

// 本地状态来管理进度更新
const localDuplicateGroups = ref(0)
const localSavedSpace = ref(0)
const localScannedFiles = ref(0)

// 取消扫描确认对话框状态
const showCancelConfirm = ref(false)

// 自动滚动到底部
const scrollToBottom = () => {
  if (logContainerRef.value) {
    nextTick(() => {
      const container = logContainerRef.value!
      // 使用平滑滚动
      container.scrollTo({
        top: container.scrollHeight,
        behavior: 'smooth'
      })
    })
  }
}

// 强制滚动到底部（用于新消息）
const forceScrollToBottom = () => {
  if (logContainerRef.value) {
    nextTick(() => {
      const container = logContainerRef.value!
      // 强制滚动，不使用平滑滚动
      container.scrollTop = container.scrollHeight
    })
  }
}

// 监听scanProgress变化，实时更新显示
watch(() => props.scanProgress, (newProgress) => {
  if (!newProgress) return
  
  console.log('ScanProgress组件收到新数据:', newProgress)
  
  // 更新本地状态
  if (newProgress.scannedFiles !== undefined) {
    localScannedFiles.value = newProgress.scannedFiles
    console.log('更新已扫描文件数:', localScannedFiles.value)
  }
  if (newProgress.duplicateGroups !== undefined) {
    localDuplicateGroups.value = newProgress.duplicateGroups
    console.log('更新重复组数:', localDuplicateGroups.value)
  }
  if (newProgress.savedSpace !== undefined) {
    localSavedSpace.value = newProgress.savedSpace
    console.log('更新可节省空间:', localSavedSpace.value)
  }
  
  // 根据stage添加进度日志
  if (newProgress.stage && newProgress.message) {
    console.log('添加进度日志:', newProgress.stage, newProgress.message)
    addProgressLog(newProgress.message)
  }
  
  // 更新当前文件显示
  if (newProgress.message && newProgress.message.includes('文件哈希已缓存:')) {
    currentFile.value = newProgress.message.split('文件哈希已缓存: ')[1]
    setTimeout(() => {
      currentFile.value = ''
    }, 2000)
  }
}, { deep: true, immediate: true })

// 添加进度日志
const addProgressLog = (message: string) => {
  const log: ProgressLog = {
    timestamp: Date.now(),
    message: message
  }
  progressLogs.value.push(log)
  
  // 限制日志数量，避免内存占用过大
  if (progressLogs.value.length > 1000) {
    progressLogs.value = progressLogs.value.slice(-500)
  }
  
  // 强制滚动到底部，确保新消息可见
  forceScrollToBottom()
}

// 计算当前状态 - 基于后端message
const currentStatus = computed(() => {
  const message = props.scanProgress.message
  console.log('计算当前状态，message:', message)
  
  if (message) {
    if (message.includes('正在扫描目录文件')) return '正在扫描文件...'
    if (message.includes('文件扫描完成')) return '文件扫描完成'
    if (message.includes('正在计算文件哈希值')) return '正在计算文件哈希值...'  // 新增
    if (message.includes('文件哈希值计算完成')) return '文件哈希值计算完成'      // 新增
    if (message.includes('正在分析重复文件')) return '正在分析重复文件...'
    if (message.includes('重复文件分析完成')) return '重复文件分析完成'
    if (message.includes('扫描完成')) return '扫描完成'
    return message
  }
  return '准备开始扫描...'
})

// 计算子状态
const currentSubStatus = computed(() => {
  const message = props.scanProgress.message
  if (message) {
    if (message.includes('发现') && message.includes('个文件')) {
      return `已发现 ${localScannedFiles.value} 个文件`
    }
    if (message.includes('发现') && message.includes('个重复组')) {
      return `已发现 ${localDuplicateGroups.value} 个重复组`
    }
    if (message.includes('可节省空间')) {
      return `可节省空间 ${savedSpaceDisplay.value}`
    }
  }
  return props.scanProgress.subStatus || '等待中...'
})

// 计算已扫描文件状态
const scannedFilesStatus = computed(() => {
  if (props.scanProgress.stage === 'completed') return '已完成'
  if (localScannedFiles.value > 0) return `已发现 ${localScannedFiles.value} 个`
  return '等待中...'
})

// 计算重复组数显示
const duplicateGroupsCount = computed(() => {
  return localDuplicateGroups.value || props.scanProgress.duplicateGroups || 0
})

// 计算重复组数状态
const duplicateGroupsStatus = computed(() => {
  if (props.scanProgress.stage === 'completed') return '已完成'
  if (props.scanProgress.stage === 'duplicates_analyzed') return '分析完成'
  if (props.scanProgress.stage === 'analyzing_duplicates') return '分析中...'
  if (duplicateGroupsCount.value > 0) return `已发现 ${duplicateGroupsCount.value} 组`
  return '等待中...'
})

// 计算可节省空间显示
const savedSpaceDisplay = computed(() => {
  const space = localSavedSpace.value || props.scanProgress.savedSpace
  if (space === null || space === undefined || isNaN(space) || space < 0) {
    return '0 B'
  }
  return formatFileSize(space)
})

// 计算可节省空间状态
const savedSpaceStatus = computed(() => {
  if (props.scanProgress.stage === 'completed') return '已完成'
  if (props.scanProgress.stage === 'duplicates_analyzed') return '计算完成'
  if (props.scanProgress.stage === 'analyzing_duplicates') return '计算中...'
  if (savedSpaceDisplay.value !== '0 B') return '已计算'
  return '等待中...'
})

// 判断扫描是否完成
const isScanCompleted = computed(() => {
  return props.scanProgress.stage === 'completed' && props.scanProgress.message === '扫描完成'
})

// 格式化时间
const formatTime = (timestamp: number): string => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { 
    hour12: false, 
    hour: '2-digit', 
    minute: '2-digit', 
    second: '2-digit' 
  })
}

// 格式化文件大小 - 修复NaN问题
const formatFileSize = (bytes: number): string => {
  // 检查是否为有效数字
  if (bytes === null || bytes === undefined || isNaN(bytes) || bytes < 0) {
    return '0 B'
  }
  
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 取消扫描 - 这个版本只是console.log，不会改变页面
const cancelScan = () => {
  console.log('取消扫描')
  // 这个版本没有emit，所以页面不会有任何变化
  showCancelConfirm.value = true
}

// 确认取消扫描
const confirmCancel = () => {
  console.log('用户确认取消扫描')
  emit('cancel-scan')
  showCancelConfirm.value = false
}

// 继续扫描
const continueScan = () => {
  console.log('用户选择继续扫描')
  showCancelConfirm.value = false
}

// 停止扫描
const stopScan = () => {
  console.log('用户点击停止扫描')
  emit('cancel-scan')
}

// 组件挂载时初始化
onMounted(() => {
  // 添加初始日志
  addProgressLog('等待扫描开始...')
})
</script>

<style scoped>
/* 日志文字选择样式 */
.font-mono {
  user-select: text;
  -webkit-user-select: text;
}
</style>
